﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Shared.Service.Authorizations.Authorization.HttpApis;
using Shared.Service.DataScopes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Yyd.Share.Base;

namespace Shared.Service.Authorizations.Authorization.DataScopes
{
    public class DataScopeStore : IDataScopeStore, ITransientDependency
    {
        public ILogger<DataScopeStore> Logger { get; set; }

        protected IDistributedCache Cache { get; }

        private readonly IDataScopesHttpApi _dataScopesHttpApi;
 

        public static DistributedCacheEntryOptions DefaultCacheEntryOption = new DistributedCacheEntryOptions
            { SlidingExpiration = TimeSpan.FromSeconds(30) };

 


 

        public async Task<List<DataScopeInfo>> GetDataScopesAsync(string name, string providerName, string providerKey)
        {

            var dataScopeCache = await GetCacheItemAsync(name, providerName, providerKey).ConfigureAwait(false);

            if (dataScopeCache == null)
            {
                return new List<DataScopeInfo>();
            }

            return dataScopeCache.Items
                ?.Select(ds => new DataScopeInfo(name, providerName, providerKey, ds.ScopeType, ds.ScopeKeys)).ToList();
        }

        protected virtual async Task<DataScopeCache> GetCacheItemAsync(string name, string providerName,
            string providerKey)
        {
            var cacheKey = DataScopeCache.CalculateCacheKey(name, providerName, providerKey);

            // 获取缓存数据
            var cacheValue = await Cache.GetAsync(cacheKey).ConfigureAwait(false);

            if (cacheValue != null)
            {
                return new DataScopeCache();
            }

            //var dataScopeCaches = (await GetDataScopeList(name, providerName, providerKey))
            //    .Select(ds => new DataScopeCacheItem(ds.ScopeType, ds.ScopeKeys));
            //cacheValue = new DataScopeCache(name, dataScopeCaches.ToArray());

            // 缓存写入
            // await Cache.SetAsync(cacheKey, cacheValue, GetDefauleCacheEntryOption()).ConfigureAwait(false);

            return new DataScopeCache();
        }

        protected virtual async Task<List<DataScopeInfo>> GetDataScopeList(string name, string providerName,
            string providerKey)
        {
            var result = new List<DataScopeInfo>();

            try
            {
                var resultData = await _dataScopesHttpApi.GetUserDataScopesAsync(
                    new GetUserDataScopesRequest( providerKey, name));


                //var resultData = new Dictionary<string, string[]>();
                //////////resultData.Add("mine", new[] { "USER20200409010000014319" });
                //resultData.Add("myDept", new[] { "DPT20200409010000000033" });

                //resultData.Add("myArea", new[] { (string)null });
                //resultData.Add("allProject", new[] { "DPT20200409010000002413" });
                //resultData.Add("allUsersource", Array.Empty<string>());

                // 商户中的本门店
                //resultData.Add("myOrgSchool", new[] { "DPT20200409010000003900" });
                //resultData.Add("mySchool", new[] { "SCHOOL20210919770000000036" });
                //resultData.Add("allProject", new[] { "DPT20200409010000002413" });
                //resultData.Add("allUsersource", Array.Empty<string>());



                //resultData.Add("myOrgSchool", new[] { "DPT20200409010000002374" });
                //resultData.Add("mySchool", new[] { "SCHOOL20200229880000000001" });
                //resultData.Add("allProject", new[] { "DPT20200409010000002413" });
                //resultData.Add("allUsersource", Array.Empty<string>());


                foreach (var item in resultData ?? new Dictionary<string, string[]>())
                {
                    var scopeType = ParseDataScopeType(item.Key);
                    if (scopeType != DataScopeType.Null)
                    {
                        result.Add(new DataScopeInfo(name, providerName, providerKey, scopeType, item.Value));
                    }
                }
            }
            catch (Exception e)
            {
                throw new OperationException("获取数据范围api时发生错误！授权名称：" + name + "，详细信息：" + (e.InnerException?.Message ?? e.Message));
            }




            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="scopeType"></param>
        /// <returns></returns>
        private DataScopeType ParseDataScopeType(string scopeType) => scopeType switch
        {
            "createdByMe" => DataScopeType.MyCreated,
            "mine" => DataScopeType.Myself,

            "mySchool" => DataScopeType.MySchool,

            "myDept" => DataScopeType.MyOrgDept,
            "myOrgSchool" => DataScopeType.MyOrgSchool,
            "myArea" => DataScopeType.MyOrgArea,
            "otherDept" => DataScopeType.MyOtherOrgs,
            "allDpt" => DataScopeType.OrgAll,

            "allProject" => DataScopeType.ProjectAll,
            "project" => DataScopeType.Project,
            "projectLevelcode" => DataScopeType.ProjectLevelCode,

            "allUsersource" => DataScopeType.UserSourceAll,
            "usersource" => DataScopeType.UserSource,
            "usersourceLevelcode" => DataScopeType.UserSourceLevelCode,
  
            _ => DataScopeType.Null
        };

        protected virtual DistributedCacheEntryOptions GetDefauleCacheEntryOption()
        {
            return new DistributedCacheEntryOptions();// PermissionOptions.CacheEntry ?? DefaultCacheEntryOption;
        }
    }
}
